<template>
  <div class="scroll-show">
    <div class="content clearfix">
      <!-- <cateNav
        class="cate"
        :hover="true"
        :showNavBar="false"
        useClass="fixed-show"
      ></cateNav> -->
      <div class="search-boxi">
        <!-- <Search class="search-con" :hover="true" ref="search" :showLogo="false" :showTag="false" useClass="fixed-show">
        </Search> -->
        <Search />
        <!-- <div class="search-boxi_botton" v-if="role == 'user'" @click="NewSearch">新增需求</div> -->
      </div>

      <!-- <div class="flex flex-a-c cart">
        <Icon
          type="ios-cart-outline"
          @click="goCartList"
          class="cart-icon"
          @mouseenter.native="getCartList"
        />
        <i class="cart-badge">{{ cartNum < 100 ? cartNum : "99" }}</i>
      </div> -->·
    </div>
    <Modal v-model="modal" :title="title" width="70%">
      <Form ref="formValidates" :model="formValidate" :rules="ruleValidate" :label-width="100">
        <Row>
          <Col span="11">
          <FormItem label="需求类型" prop="type">
            <Select v-model="clickType" multiple placeholder="请选择需求类型" @on-change="clickTypeFun">
              <Option v-for="(item, i) in type" :value="item.value" :key="i">{{ item.label }}</Option>
              <!-- <Option value="shanghai">ppt</Option>
              <Option value="shenzhen">pdf</Option>
              <Option value="other">其他</Option> -->
            </Select>
          </FormItem>
          </Col>
          <Col span="11">
          <FormItem label="需求标题" prop="title">
            <Input v-model="formValidate.title" placeholder="请输入需求标题"></Input>
          </FormItem>
          </Col>
        </Row>

        <Row>
          <Col span="11">
          <FormItem label="需求描述" prop="content">
            <Input v-model="formValidate.content" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入需求描述"></Input>
          </FormItem>
          </Col>
          <Col span="11">
          <FormItem label="附件上传" prop="file">
            <FileUpload @input="FileUploadInput"></FileUpload>
          </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="11">
          <FormItem label="佣金金额" prop="price">
            <Input v-model="formValidate.price" placeholder="请输入佣金金额"></Input>
          </FormItem>
          </Col>
          <Col span="11">
          <FormItem label="需求起止时间" prop="startTime">
            <DatePicker type="datetimerange" v-model="date" @on-change="handleClickDate" placeholder="开始时间-结束时间"
              style="width: 240px" />
          </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span="11">
          <FormItem label="备注">
            <Input v-model="formValidate.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入备注"></Input>
          </FormItem>
          </Col>
          <Col span="11">
          <FormItem label="其他需求">
            <Input v-model="formValidate.other" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="请输入其他需求"></Input>
          </FormItem>
          </Col>
        </Row>
        <Checkbox v-model="single">协议勾选有客户提供二次点击后跳转内容</Checkbox>
      </Form>
      <div slot="footer">
        <Button @click="cancel">取消</Button>
        <Button style="background-color: #ff5343;color: #fff;" @click="handleSubmit('formValidates')">确认</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { cartCount } from "@/api/cart.js";
import storage from "@/plugins/storage.js";
import { Message, Spin, Modal } from 'view-design';
import { EventBus } from '@/plugins/EventBus';
import { saveDesired, getOrderTypeList } from "@/api/writer/index.js";
export default {
  data() {
    return {
      userInfo: {}, // 用户信息
      modal: false,
      title: "新增需求",
      single: false,
      formValidate: {
        type: null,
        title: '',
        content: '',
        file: '',
        price: null,
        remark: '',
        other: '',
        startTime: '',
        endTime: '',
      },
      clickType: [],
      date: [],//日期
      type: [],//需求类型
      ruleValidate: {
        type: [
          { required: true, message: '请选择需求类型', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入需求标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入需求描述', trigger: 'blur' }
        ],
        file: [
          { required: true, message: '请选择附件上传', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入佣金金额', trigger: 'blur' },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入整数或两位小数',
            trigger: 'change'
          }
        ],
        startTime: [
          { required: true, message: '请选择日期', trigger: 'change' }
        ],
      },
      role: ''
    };
  },
  computed: {
    cartNum() {
      // 购物车商品数量
      return this.$store.state.cartNum;
    },
  },
  mounted() {
    this.GetOrderTypeList();

    if (storage.getItem("userInfo")) {
      this.userInfo = JSON.parse(storage.getItem("userInfo"));
    }
    if (storage.getItem("roles")) {
      this.role = storage.getItem("roles")
      console.log(this.role, "this.role");

    }
  },
  methods: {
    NewSearch() {
      const storedToken = storage.getItem('accessToken');
      const storedTime = storage.getItem('tokenTime');
      if (storedToken && storedTime) {
        const now = new Date().getTime();
        const diff = (now - parseInt(storedTime)) / (1000 * 60); // 计算时间差（分钟）
        if (diff > 300) {
          storage.removeItem('accessToken');
          storage.removeItem('refreshToken');
          storage.removeItem('userInfo');
          storage.removeItem('roles');
          Modal.confirm({
            title: '请登录',
            content: `<p>token已过期请重新登录</p>`,
            okText: '立即登录',
            cancelText: '继续浏览',
            onOk: () => {
              this.$router.push({
                path: '/login',
                query: {
                  rePath: this.$router.history.current.path,
                  query: JSON.stringify(this.$router.history.current.query)
                }
              });
            },
            onCancel: () => {
              // router.go(0)
              this.$router.push("/");
              Modal.remove();
            }
          });
        } else {
          this.$refs.formValidates.resetFields();
          this.clickType = ''
          this.single = false
          this.modal = true;
          this.title = "新增需求";
        }
      } else {
        storage.removeItem('accessToken');
        storage.removeItem('refreshToken');
        storage.removeItem('userInfo');
        storage.removeItem('roles');
        Modal.confirm({
          title: '请登录',
          content: `<p>请先登录在执行此操作</p>`,
          okText: '立即登录',
          cancelText: '继续浏览',
          onOk: () => {
            this.$router.push({
              path: '/login',
              query: {
                rePath: this.$router.history.current.path,
                query: JSON.stringify(this.$router.history.current.query)
              }
            });
          },
          onCancel: () => {
            // router.go(0)
            this.$router.push("/");
            Modal.remove();
          }
        });
      }
    },
    goCartList() {
      // 跳转购物车页面
      let routerUrl = this.$router.resolve({
        path: "/cart",
      });
      window.open(routerUrl.href, "_blank");
    },
    getCartList() {
      // 获取购物车列表
      if (storage.getItem("userInfo")) {
        cartCount().then((res) => {
          this.$store.commit("SET_CARTNUM", res.result);
          this.Cookies.setItem("cartNum", res.result);
        });
      }
    },
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (!this.single) {
            this.$Message.error('请勾选协议!');
            return
          }
          const params = {
            id: 0,
            userId: JSON.parse(storage.getItem("userInfo")).userId,
            ...this.formValidate,
          }
          saveDesired(params).then(res => {
            console.log(res, "保存需求订单");
            if (res.code == 200) {
              this.$Message.success('保存成功!');
              EventBus.$emit('message', 'Hello from Component A');
              this.modal = false;
            }
          })

        } else {
          this.$Message.error('请填写完整信息!');
        }
      })
    },
    cancel() {
      this.$refs.formValidates.resetFields();
      this.modal = false;
    },
    //获取订单类型
    GetOrderTypeList() {
      getOrderTypeList().then(res => {
        this.type = res.data.map(x => {
          return {
            label: x.name,
            value: x.id
          }
        })
      })
    },
    //日期选择
    handleClickDate(val) {
      console.log(val, "val");
      this.formValidate.startTime = val[0]
      this.formValidate.endTime = val[1]
    },
    //上传附件
    FileUploadInput(file) {
      // console.log(file, "file");
      this.formValidate.file = file
    },
    clickTypeFun(val) {
      console.log(val, "val");
      this.formValidate.type = val.join(',')
    }
  },
};
</script>
<style lang="scss" scoped>
.content {
  width: 1200px;
  height: 40px;
  margin: 0 auto;
  position: relative;
}

.cate {
  float: left;
  width: 200px !important;
}



.cart {
  height: 60px;
}

.cart-icon {
  width: 30px;
  float: left;
  font-size: 25px;

  color: $theme_color;
  z-index: 1;
  position: relative;

  &:hover {
    cursor: pointer;
  }
}

.cart-badge {
  position: absolute;
  font-style: normal;
  right: 165px;
  display: block;
  background-color: $theme_color;
  color: #fff;
  font-size: 12px;
  width: 17px;
  height: 17px;
  border-radius: 10px;
  line-height: 17px;
  text-align: center;
  z-index: 5;
  top: 10px;
}

.search-boxi {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;

  .search-con {
    float: left;
    width: 800px;
    overflow: hidden;
    margin-top: -27px;
  }

  .search-boxi_botton {
    background-color: #f31947;
    color: #ffffff;
    padding: 12px 30px;
    border-radius: 25px;
    cursor: pointer;
  }
}
</style>
